package com.starbaba.pushservice.view;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.http.HttpClientUtil;
import com.base.common.http.model.FormData;
import com.base.common.http.model.HttpResult;
import com.base.common.http.model.PostData;
import com.base.common.log.LogService;
import com.google.gson.*;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.model.db.Short_Link;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.model.network.Phead;
import com.starbaba.model.utils.HttpConnectionUtils;
import com.starbaba.model.utils.JSONUtils;
import com.starbaba.model.utils.ZipUtil;
import com.starbaba.pushservice.model.PushActionModel;
import com.starbaba.pushservice.service.PushActionService;
import com.starbaba.stat.model.RegionVO;
import com.starbaba.stat.utils.RegionInfoHandler;
import com.starbaba.tools.sequence.IntUtil;
import com.starbaba.tools.sequence.Sequence;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PushAction extends BaseAction implements
		ModelDriven<PushActionModel> {

	private static final long serialVersionUID = 7572967277476911521L;
	private static final int PUSH_SERVICE_TIMEOUT = 30000;

	// 推送后台的数据单元
	PushActionModel model;
	// 推送后台的业务逻辑处理
	PushActionService server;

	/**
	 * 创建新消息的方法 这里什么都没赶，直接返回成功，跳转到创建消息的页面
	 * 
	 * @return
	 */
	public String createNewMessage() {
		return ActionSupport.SUCCESS;
	}

	/**
	 * 上传消息图标的方法
	 */
	public void uploadMessageIcon() {
		String url = null;
		// 把图标上传到7牛服务器
		if (server != null && model != null) {
			url = server.uploadMessageIcon(model);
		}
		// 返回生成的url给客户端
		JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty("url", url);
		try {
			sendJsonMessage(jsonObject.toString());
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * 获取所有省份信息的方法
	 */
	public void getProvinces() {
		RegionInfoHandler instance = RegionInfoHandler.getInstance();
		List<RegionVO> provinces = instance.getPrivonce(this.getService());
		JsonArray jsonArray = new JsonArray();
		for (RegionVO province : provinces) {
			// 排除未知这个项
			if (province != null && province.getName().equals("未知")) {
				continue;
			}
			JsonObject jsonObject = new JsonObject();
			jsonObject.addProperty("id", province.getId());
			jsonObject.addProperty("pid", province.getPid());
			jsonObject.addProperty("name", province.getName());
			jsonArray.add(jsonObject);
		}
		try {
			sendJsonMessage(jsonArray.toString());
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * 获取省份底下所有城市信息的方法
	 */
	public void getCityForProvince() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		JsonArray jsonArray = new JsonArray();
		if (paramsMap != null && paramsMap.get("provinceId") != null) {
			String provinceId = String.valueOf(paramsMap.get("provinceId"));
			RegionInfoHandler instance = RegionInfoHandler.getInstance();
			List<RegionVO> citys = instance.getCityFromPrivonce(
					this.getService(), provinceId);
			for (RegionVO city : citys) {
				// 排除未知这个项
				if (city != null && city.getName().equals("未知")) {
					continue;
				}
				JsonObject jsonObject = new JsonObject();
				jsonObject.addProperty("id", city.getId());
				jsonObject.addProperty("pid", city.getPid());
				jsonObject.addProperty("name", city.getName());
				jsonArray.add(jsonObject);
			}
		}
		try {
			sendJsonMessage(jsonArray.toString());
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	/**
	 * 推送消息的方法
	 */
	@SuppressWarnings("deprecation")
	public void pushmessage() {
		
		BaseDao testDao = new BaseDao(Constant.POOL_LIFE);
		
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
			
		String request = (String) paramsMap.get("request");
		request = request.replace("%26", "&");
		request = request.replace("%25", "%");
		JsonElement jsonElement = new JsonParser().parse(request);
		String data = jsonElement.getAsJsonObject().get("data").toString();
		
		JsonElement msg_tmp = jsonElement.getAsJsonObject().get("data").getAsJsonObject().get("msg");
		String htmlurl = "";// 原始链接
		String myurl = "";// 转换链接
		String slink = "";// 短链接
		if (msg_tmp != null) {// 如果链接不为空，把链接转换成可以统计的链接
			JsonElement responseParams_tmp = msg_tmp.getAsJsonObject().get("responseParams");
			if (responseParams_tmp != null) {
				JsonElement launchParams_tmp = responseParams_tmp.getAsJsonObject().get("launchParams");
				if (launchParams_tmp != null) {
					JsonElement htmlUrl_tmp = launchParams_tmp.getAsJsonObject().get("htmlUrl");
					if (htmlUrl_tmp != null) {
						htmlurl = htmlUrl_tmp.getAsString();
						
						String soruceurl = htmlurl;
						Short_Link link = new Short_Link();
						Long id = Sequence.getSequence();
						link.setId(id);
						link.setUrl(soruceurl);
						link.setCtime(new Date());
						slink = IntUtil.couponGen(id, 5);
						link.setShort_link(slink);
						link.setActivity("推送");
						link.setMemo("推送");
						link.setUnit_price(0f);
						try {
							String common_host = Constant.COMMON_HOST;
							if (common_host.contains("chezhuwuyou")) {
								testDao.add(
										"insert into starbaba.short_link (id, url, short_link, memo, ctime, unit_price, activity) values (?,?,?,?,?,?,?) ",
										link.getId(), link.getUrl(),
										link.getShort_link(), link.getMemo(),
										link.getCtime(), link.getUnit_price(),
										link.getActivity());

								Gson gson = new GsonBuilder().disableHtmlEscaping().create();
								String sourceResult = gson.toJson(link);
								String key = "redict_new_" + slink;
								ArrayList<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
								list.add(new BasicNameValuePair("key", key));
								list.add(new BasicNameValuePair("value", sourceResult));
								HttpConnectionUtils.connection(Constant.COMMON_HOST + "/mredis/oper/set", HttpConnectionUtils.POST, list);
								myurl = Constant.COMMON_HOST + "/share/redirect?from=" + slink;
								
							} else {
								testDao.add(link);
								myurl = Constant.COMMON_HOST + "/share_service/redirect?from=" + slink;
							}
						} catch (AppException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		
		if (StringUtils.isNotEmpty(htmlurl)) {
			data = data.replace(htmlurl, myurl);
		}
		LogService.info("push action : sendType," + data);
		FormData formdata = new FormData();
		formdata.addParam("handle", "0");
		formdata.addParam("data", data);
		formdata.addParam("shandle", "0");
		PostData postData = new PostData(formdata);

		String record_id = (String) paramsMap.get("record_id");
		String ismysql = (String) paramsMap.get("ismysql");
		String pushcontent = (String) paramsMap.get("pushcontent");
		
		String msg = "";
		String android_content = "";
		if (msg_tmp != null) {
			msg = msg_tmp.toString().replace(htmlurl, myurl);
			JsonElement android_content_tmp = msg_tmp.getAsJsonObject().get("content");
			if (android_content_tmp != null) {
				android_content = android_content_tmp.getAsString();
			}
		}
		
		JsonElement send_date_tmp = jsonElement.getAsJsonObject().get("data").getAsJsonObject().get("send_date");
		String send_date = "";
		if (send_date_tmp != null) {
			send_date = send_date_tmp.getAsString();
		}
		JsonElement lockkey_tmp = jsonElement.getAsJsonObject().get("data").getAsJsonObject().get("lockkey");
		String lockkey = "";
		if (lockkey_tmp != null) {
			lockkey = lockkey_tmp.getAsString();
		}
		JsonElement userid_tmp = jsonElement.getAsJsonObject().get("data").getAsJsonObject().get("userid");
		String userid = "-1";
		if (userid_tmp != null) {
			userid = userid_tmp.getAsString();
		}
		JsonElement platfrom_tmp = jsonElement.getAsJsonObject().get("data").getAsJsonObject().get("platfrom");
		String platfrom = "";
		if (platfrom_tmp != null) {
			platfrom = platfrom_tmp.getAsString();
		}
		if ("1".equals(platfrom)) {
			platfrom = "android";
		} else if ("2".equals(platfrom)) {
			platfrom = "ios";
		} else {
			platfrom = "all";
		}
		// 单发：0 ; 群发：1
		String sendtype = "0";
		if (Integer.parseInt(userid) < 0) {
			sendtype = "1";
		}
		
		LogService.info("push action : sendType," + sendtype);
		 
		JsonElement expiredate_tmp = jsonElement.getAsJsonObject().get("data").getAsJsonObject().get("expiredate");
		String expiredate = "";
		if (expiredate_tmp != null) {
			expiredate = expiredate_tmp.getAsString();
		}
		JsonElement tags_tmp = jsonElement.getAsJsonObject().get("data").getAsJsonObject().get("tags");
		String tags = "";
		if (tags_tmp != null) {
			tags = tags_tmp.getAsString();
		}
		JsonElement product_id_tmp = jsonElement.getAsJsonObject().get("data").getAsJsonObject().get("product_id");
		String product_id = "";
		if (product_id_tmp != null) {
			product_id = product_id_tmp.getAsString();
		}
		JsonElement provinceids_tmp = jsonElement.getAsJsonObject().get("data").getAsJsonObject().get("provinceids");
		String provinceids = "";
		if (provinceids_tmp != null) {
			provinceids = provinceids_tmp.getAsString();
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date nowDate = new Date();
		String responsedata = "{\"result\": {\"status\": 2},\"costTime\": 999}";
		if (StringUtils.isNotEmpty(send_date)) {
			try {
				Date sendDate = sdf.parse(send_date);
				if (nowDate.after(sendDate)) {
					sendJsonMessage(responsedata);
					return ;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		String createtime = sdf.format(nowDate);
		
		if (record_id == null) {
			// 新增,将推送任务存任务表
			StringBuilder insert_sql = new StringBuilder("INSERT INTO push_message_task (slink, htmlurl, createtime, createid, status, sendtype, senduserid, ");
			StringBuilder findid_sql = new StringBuilder("SELECT id FROM push_message_task WHERE slink = ? AND htmlurl = ? AND createtime = ? AND createid = ? AND status = ? AND sendtype = ? AND senduserid = ? ");
			List<Object> params = new ArrayList<>();
			params.add(slink);
			params.add(htmlurl);
			params.add(createtime);
			params.add(getUserVO().getUserid());
			if (StringUtils.isEmpty(send_date)) {
				params.add(3);
			} else {
				params.add(1);
			}
			params.add(sendtype);
			params.add(userid);
			int i = 8;
			if (msg_tmp != null && !"".equals(msg)) {
				insert_sql.append("content, ");
				findid_sql.append("AND content = ? ");
				params.add(msg);
				i++;
			}
			if (StringUtils.isNotEmpty(send_date)) {
				insert_sql.append("sendtime, senddate, ");
				findid_sql.append("AND sendtime = ? AND senddate = ? ");
				params.add(send_date);
				params.add(send_date.substring(0, 10));
				i++;
			} else {
				insert_sql.append("sendtime, senddate, ");
				findid_sql.append("AND sendtime = ? AND senddate = ? ");
				params.add(createtime);
				params.add(createtime.substring(0, 10));
				i++;
			}
			if (platfrom_tmp != null && !"all".equals(platfrom)) {
				insert_sql.append("platfrom, ");
				findid_sql.append("AND platfrom = ? ");
				params.add(platfrom);
				i++;
			}
			if (product_id_tmp != null && !"".equals(product_id)) {
				insert_sql.append("sendproduct, ");
				findid_sql.append("AND sendproduct = ? ");
				params.add(product_id);
				i++;
			}
			if (expiredate_tmp != null && !"".equals(expiredate)) {
				insert_sql.append("endtime, ");
				findid_sql.append("AND endtime = ? ");
				params.add(expiredate);
				i++;
			}
			if (lockkey_tmp != null && !"".equals(lockkey)) {
				insert_sql.append("isocontent, ");
				findid_sql.append("AND isocontent = ? ");
				params.add(lockkey);
				i++;
			}
			if (provinceids_tmp!=null&&!"".equals(provinceids)) {
				insert_sql.append("provinceid, ");
				findid_sql.append("AND provinceid = ? ");
				params.add(provinceids);
				i++;
			}
			if (tags_tmp != null && !"".equals(tags)) {
				insert_sql.append("tags, ");
				findid_sql.append("AND tags = ? ");
				params.add(tags);
				i++;
			}
			String insert_sql_tmp = insert_sql.toString();
			insert_sql_tmp = insert_sql_tmp.substring(0, insert_sql_tmp.length() - 2);
			insert_sql_tmp += ") VALUES (";
			for (int j = 0; j < i; j++) {
				insert_sql_tmp += "?, ";
			}
			insert_sql_tmp = insert_sql_tmp.substring(0, insert_sql_tmp.length() - 2);
			insert_sql_tmp += ")";
			try {
				Long id = testDao.addReturnGeneratedKey(insert_sql_tmp, params);
				LogService.info("push action : add task ,id " + id);
				if (StringUtils.isEmpty(send_date)) {
					// 立即发送
					String postUrl = Constant.COMMON_HOST + "/push_service/common?funid=999&rd=" + System.currentTimeMillis();
				
					LogService.info("push action : postUrl," + postUrl);
					// 请求数据
					HttpClientUtil.createHttpClient("push_service", PUSH_SERVICE_TIMEOUT, PUSH_SERVICE_TIMEOUT, 200, 200);
					HttpResult httpResult = HttpClientUtil.post("push_service", postUrl, postData);
					responsedata = httpResult.getStringData();
					LogService.info("push action : send immediately," + responsedata);
				} else {
					// 定时推送
					String autoPostUrl = Constant.COMMON_HOST + "/push_service/common?funid=1&rd=" + System.currentTimeMillis();
					
					FormData fd_start = new FormData();
					JsonObject start_obj = new JsonObject();
					start_obj.add("phead", JSONUtils.toJsonObject(new Phead()));
					start_obj.addProperty("id", id);
					start_obj.addProperty("op", 1);
					fd_start.addParam("handle", "0");
					fd_start.addParam("data", start_obj.toString());
					fd_start.addParam("shandle", "1");
					PostData pd_start = new PostData(fd_start);
					
					HttpResult httpResult = HttpClientUtil.post(autoPostUrl, pd_start);
					responsedata = ZipUtil.unCompressData(httpResult.getData());
				}
				
				if ("yes".equals(ismysql)) {
					// 将推送结果记录存记录表	
					StringBuilder sb = new StringBuilder("INSERT INTO push_message_record (slink, pushid, createtime, sendtime, senddate, content, android_content, ios_content, platfrom, createid) VALUES (?,?,?,?,?,?,?,?,?,?)");
					List<Object> params2 = new ArrayList<Object>();
					params2.add(slink);
					params2.add(id);
					params2.add(createtime);
					if (StringUtils.isEmpty(send_date)) {
						params2.add(createtime);
						params2.add(createtime.substring(0, 10));
					} else {
						params2.add(send_date);
						params2.add(send_date.substring(0, 10));
					}
					params2.add(pushcontent);
					params2.add(android_content);
					params2.add(lockkey);
					params2.add(platfrom);
					params2.add(getUserVO().getUserid());
					testDao.add(sb.toString(), params2);
				}
				LogService.info("push action : response," + responsedata);
				sendJsonMessage(responsedata);
			} catch (Exception e) {
				LogService.error(e);
			}
			
		} else {// 修改推送记录
			try {
				
				// 暂停旧的定时推送，更新定时推送的数据库信息，再开启定时任务
				Integer pushid = testDao.getInt("SELECT pushid FROM push_message_record WHERE id = ?", record_id);
				
//				FormData fd_stop = new FormData();
//				JsonObject stop_obj = new JsonObject();
//				stop_obj.add("phead", JSONUtils.toJsonObject(new Phead()));
//				stop_obj.addProperty("id", pushid);
//				stop_obj.addProperty("op", 3);
//				fd_stop.addParam("handle", "0");
//				fd_stop.addParam("data", stop_obj.toString());
//				fd_stop.addParam("shandle", "1");
//				PostData pd_stop = new PostData(fd_stop);
//
//				String autoPausePostUrl = Constant.COMMON_HOST + "/push_service/common?funid=1&rd=" + System.currentTimeMillis();
//				HttpResult httpResult2 = HttpClientUtil.post(autoPausePostUrl, pd_stop);
//				String result = ZipUtil.unCompressData(httpResult2.getData());
//				LogService.info(result);
				 
				// 更新推送的任务表
				StringBuilder update_sql = new StringBuilder("UPDATE push_message_task SET slink = ?, htmlurl = ?, createid = ?, status = ?, sendtype = ?, senduserid = ?, ");
				List<Object> params = new ArrayList<>();
				params.add(slink);
				params.add(htmlurl);
				params.add(getUserVO().getUserid());
				if (StringUtils.isNotEmpty(send_date)) {
					params.add(1);
					params.add(sendtype);
					params.add(userid);
					update_sql.append("sendtime = ?, senddate = ?, ");
					params.add(send_date);
					params.add(send_date.substring(0, 10));
				} else {
					params.add(3);
					params.add(sendtype);
					params.add(userid);
					update_sql.append("sendtime = ?, senddate = ?, ");
					String sendtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
					params.add(sendtime);
					params.add(sendtime.substring(0, 10));
				}
				if (msg_tmp != null && !"".equals(msg)) {
					update_sql.append("content = ?, ");
					params.add(msg);
				}
				if (platfrom_tmp != null & !"".equals(platfrom)) {
					update_sql.append("platfrom = ?, ");
					params.add(platfrom);
				}
				if (product_id_tmp != null && !"".equals(product_id)) {
					update_sql.append("sendproduct = ?, ");
					params.add(product_id);
				}
				if (expiredate_tmp != null && !"".equals(expiredate)) {
					update_sql.append("endtime = ?, ");
					params.add(expiredate);
				}
				if (lockkey_tmp != null && !"".equals(lockkey)) {
					update_sql.append("isocontent = ?, ");
					params.add(lockkey);
				}
				if (provinceids_tmp!=null&&!"".equals(provinceids)) {
					update_sql.append("provinceid = ?, ");
					params.add(provinceids);
				}
				if (tags_tmp != null && !"".equals(tags)) {
					update_sql.append("tags = ?, ");
					params.add(tags);
				}
				String insert_sql_tmp = update_sql.toString();
				insert_sql_tmp = insert_sql_tmp.substring(0, insert_sql_tmp.length() - 2);
				insert_sql_tmp += " where id = ?";
				params.add(pushid);
				testDao.update(insert_sql_tmp.toString(), params);
				
				FormData fd_edit = new FormData();
				JsonObject edit_obj = new JsonObject();
				edit_obj.add("phead", JSONUtils.toJsonObject(new Phead()));
				edit_obj.addProperty("id", pushid);
				edit_obj.addProperty("op", 2);
				fd_edit.addParam("handle", "0");
				fd_edit.addParam("data", edit_obj.toString());
				fd_edit.addParam("shandle", "1");
				PostData pd_eidt = new PostData(fd_edit);
				
				String autoPostUrl = Constant.COMMON_HOST + "/push_service/common?funid=1&rd=" + System.currentTimeMillis();
//				String autoPostUrl = "http://localhost:8080/push_service/common?funid=1&rd=" + System.currentTimeMillis();
				HttpResult httpResult = HttpClientUtil.post(autoPostUrl, pd_eidt);
				
				// 更新推送的记录表
				String updatesql_record = "UPDATE push_message_record SET slink = ?, pushid = ?, sendtime = ?, senddate = ?, content = ?, android_content = ?, ios_content = ?, platfrom = ?, createid = ? where id = ?";
				List<Object> params2 = new ArrayList<>();
				params2.add(slink);
				params2.add(pushid);
				if (StringUtils.isEmpty(send_date)) {
					params2.add(createtime);
					params2.add(createtime.substring(0, 10));
				} else {
					params2.add(send_date);
					params2.add(send_date.substring(0, 10));
				}
				params2.add(pushcontent);
				params2.add(android_content);
				params2.add(lockkey);
				params2.add(platfrom);
				params2.add(getUserVO().getUserid());
				params2.add(record_id);
				
				testDao.update(updatesql_record, params2);
				responsedata = ZipUtil.unCompressData(httpResult.getData());
				sendJsonMessage(responsedata);
			} catch (Exception e) {
				LogService.error(e);
			}
		}
	}

	@Override
	public PushActionModel getModel() {
		if (model == null) {
			model = new PushActionModel();
		}
		return model;
	}

	@Autowired
	@Qualifier("pushActionServiceImpl")
	public void setServer(PushActionService server) {
		this.server = server;
	}
}
